from logging import fatal

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from unicodedata import category

from course.models import Course
from course.ser import CourseSer
from home.models import NavModel, BannerModel, CateModel
from home.ser import NavSer, BannerSer, CateSer, CategorySer


# Create your views here.
class HomeView(APIView):
    def get(self, request):
        return Response("OK")


class NavView(APIView):
    def get(self, request):
        nav = NavModel.objects.filter(is_del=1, position=1).order_by('order')
        navSer = NavSer(nav, many=True)
        return Response(navSer.data)


class ProView(APIView):
    def get(self, request):
        nav = NavModel.objects.filter(is_del=1, position=0).order_by('order')
        navSer = NavSer(nav, many=True)
        return Response(navSer.data)


class BannerView(APIView):
    def get(self, request):
        banner = BannerModel.objects.filter(is_del=1).order_by('order')
        bannerser = BannerSer(banner, many=True)
        return Response(bannerser.data)


class CateView(APIView):
    def get(self, request):
        cate = CateModel.objects.filter(is_del=1, parent=None).order_by('order')
        cateser = CategorySer(cate, many=True)
        for i in range(0, cateser.data.__len__()):
            cateser.data[i]['children'] = cateser.data[i]['children'][:3]
        return Response(cateser.data)


class CateByIdView(APIView):
    def get(self, request):
        cate = CateModel.objects.filter(is_del=1, parent=None, pk=request.query_params.get('id')).first()
        cateser = CategorySer(cate)

        catedata = CateModel.objects.filter(is_del=1, parent=request.query_params.get('id'))
        cateid = []
        for i in catedata:
            cateid.append(i.id)
        # [3,4,5]

        course = Course.objects.filter(is_del=False, is_home=True, category__in=cateid).order_by('-counts')
        courseser = CourseSer(course, many=True)

        myData = cateser.data
        myData['course'] = courseser.data[:4]
        return Response(myData)
